package org.dromara.tearoom.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;

/**
 * GeeOpen请求封装
 * @author CKJ
 * @description: TODO
 * @date 2025/4/8 17:27
 */
@Slf4j
public class GeeOpenUtil {

    private static final String LOGIN_URL = "http://manage.iot.smart-bird.cn/api/geek-iot/login";
    private static final String PUB_URL = "http://manage.iot.smart-bird.cn/api/geek-iot/device/pub";

    public static void main(String[] args) {
        getInfo("84F3EBE15342");
    }

    private static String loginAndGetToken() {
        JSONObject loginBody = JSONUtil.createObj()
                .set("username", "15827644662")
                .set("password", "Ckj123456");

        HttpResponse response = HttpRequest.post(LOGIN_URL)
                .header("Content-Type", "application/json")
                .body(loginBody.toString())
                .execute();
        log.info(response.body());
        if (response.isOk()) {
            JSONObject json = JSONUtil.parseObj(response.body());
            if(json.getInt("code")!=0){
                log.error(json.getStr("message"));
                throw new ServiceException(json.getStr("message"));
            }
            JSONObject data= JSONUtil.parseObj(json.getStr("data"));
            return data.getStr("access_token"); // 根据实际返回字段调整
        }
        return null;
    }

    public static void switchOff(String deviceKey,Integer state){
        // 1. 登录获取token
        String token = loginAndGetToken();
        if (token == null) {
            System.out.println("登录失败");
            return;
        }
        // 2. 发送命令
        JSONObject cmd = JSONUtil.createObj().set("type", "event").set("key",state);
        sendCommand(token,deviceKey,cmd);
    }

    public static void getInfo(String deviceKey){
        // 1. 登录获取token
        String token = loginAndGetToken();
        if (token == null) {
            System.out.println("登录失败");
            return;
        }
        // 2. 发送命令
        JSONObject cmd = JSONUtil.createObj().set("type", "info");
        sendCommand(token,deviceKey,cmd);
    }

    private static void sendCommand(String token,String deviceKey,JSONObject cmd) {
        JSONObject commandBody = JSONUtil.createObj()
                .set("clientId", deviceKey)
                .set("cmd", cmd.toString());

        HttpResponse response = HttpRequest.post(PUB_URL)
                .header("Content-Type", "application/json")
                .header("Authorization", "bearer "+token)
                .body(commandBody.toString())
                .execute();

        if (response.isOk()) {
            log.info("命令发送成功：{}", response.body());
        } else {
            log.error("命令发送失败：{}", response.body());
        }
    }
}
